﻿using Dapper;
using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.DLL.OrganizationDLL
{
    public class OrganizatioBusiness : Base.BaseDLL, IOrganizatioBusiness
    {
        public OrganizatioBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }


        public double GetSeq()
        {
            Organization organization = this.dbConnection.QueryFirstOrDefault<Organization>("SELECT * FROM organization WHERE havedelete=0  ORDER BY orgId DESC LIMIT 0,1");
            if (organization is null) return 1;
            else return (organization.Sequence is null ? 1 : organization.Sequence.Value + 1);
        }

        public bool IsPermissionCodeRepeat(long AutoId, string OrgCode)
        {

            string sql = $"SELECT * FROM organization WHERE orgcode='{OrgCode}'";
            if (AutoId != 0)
            {
                sql = $"{sql} AND orgId != {AutoId}";
            }
            return dbConnection.Query<Organization>(sql).Any();
        }

        public List<PageOrganizationTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   AND (orgcode LIKE '%{queryModel.KeyWord}%' OR cnname LIKE '%{queryModel.KeyWord}%'  OR enname LIKE '%{queryModel.KeyWord}%'  OR phone LIKE '%{queryModel.KeyWord}%' )";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "sequence";
                queryModel.IsAsc = false;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (queryModel.paramters.Any())
            {
                var unit = queryModel.paramters.FirstOrDefault(o => o.Label.ToLower() == "unitid");
                if (!(unit is null))
                {
                    where += $" AND unitId={unit.Value} AND parentId=0 ";
                }
                var Org = queryModel.paramters.FirstOrDefault(o => o.Label.ToLower() == "orgid");
                if (!(Org is null))
                {
                    where += $" AND parentId={Org.Value}  ";
                }
                var paramtets = queryModel.paramters.Where(o => o.Label.ToLower() != "orgid" && o.Label.ToLower() != "unitid").ToList();
                paramtets.ForEach(p =>
                {
                    where += $"  and {p.Label} like '%{p.Value}%'  ";
                });
            }
            if (queryModel.KeyWords.Any())
            {
                var unit = queryModel.KeyWords.FirstOrDefault(o => o.Label.ToLower() == "unitid");
                if (!(unit is null))
                {
                    where += $" AND unitId={unit.Value} AND parentId=0 ";
                }
                var Org = queryModel.KeyWords.FirstOrDefault(o => o.Label.ToLower() == "orgid");
                if (!(Org is null))
                {
                    where += $" AND parentId={Org.Value}  ";
                }
            }
            if (!queryModel.UseDisabledData)
            {
                where += $" AND enable=1  ";
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"SELECT count(orgid) from organization  WHERE havedelete!=1  {where} ;");
            sql.Append(@$" SELECT orgid,orgcode,cnname,enname,unitId,parentId,phone,contact,sequence,`enable`,creator,creatdate from organization  WHERE havedelete!=1 
                        {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{queryModel.PageSize} ;");
            using (var reader = dbConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageOrganizationTable> pageModules = reader.Read<PageOrganizationTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }
    }
}
